﻿using System;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YJKRevitView;

namespace YJKRevitAxisModule.AxisCut
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdGridTrim : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			this.m_doc = cmdData.Application.ActiveUIDocument.Document;
			this.m_selection = cmdData.Application.ActiveUIDocument.Selection;
			RevitVersionFuncs.ClearSelection(this.m_selection);
			CmdViewType types = (CmdViewType)15;
			if (SwitchView.SetUsableView(types, cmdData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			Autodesk.Revit.DB.View activeView = cmdData.Application.ActiveUIDocument.ActiveView;
			if (!ViewHandle.SetViewPlan(cmdData.Application.ActiveUIDocument.Document, activeView, ref msg))
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			Transaction transaction = null;
			transaction = new Transaction(this.m_doc);
			transaction.Start("trim");
			try
			{
				GridsTrimOperator gridsTrimOperator = new GridsTrimOperator(cmdData);
				Result result;
				do
				{
					result = gridsTrimOperator.Excute(ref msg);
				}
                while (result == Autodesk.Revit.UI.Result.Succeeded);
				transaction.Commit();
			}
			catch (Exception)
			{
				if (transaction != null && transaction.HasStarted() && !transaction.HasEnded())
				{
					transaction.RollBack();
				}
				return Autodesk.Revit.UI.Result.Failed;
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private Document m_doc;

		private Selection m_selection;
	}
}
